package admin

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	"goravel/app/http/requests/admin"
	"goravel/app/models/systemEntity"
)

type AuthController struct {
	// Dependent services
}

func NewAuthController() *AuthController {
	return &AuthController{
		// Inject services
	}
}

// 后台管理员登录
func (r *AuthController) Login(ctx http.Context) http.Response {
	var user_req admin.AdminRequest
	ctx.Request().Bind(&user_req)
	password := user_req.Pwd
	errors, err := ctx.Request().ValidateRequest(&user_req)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	var admin systemEntity.SystemAdmin
	//手机号密码验证
	facades.Orm().Query().Model(&admin).Where("account", user_req.Account).First(&admin)
	if admin.ID == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "用户不存在", nil)
	}
	if !facades.Hash().Check(password, admin.Pwd) {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "密码错误", nil)
	} else {
		//	生成token
		token, err1 := facades.Auth(ctx).Guard("system_admin").LoginUsingID(admin.ID)
		if err1 != nil {
			return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "服务器错误", nil)
		}
		menus, unique_auth := admin.RolesMenus()
		return ctx.Response().Status(http.StatusOK).Json(http.Json{
			"message": "登录成功",
			"data": struct {
				Token             string                     `json:"token"`
				ExpiresTime       any                        `json:"expires_time"`
				UserInfo          systemEntity.SystemAdmin   `json:"user_info"`
				Menus             []systemEntity.SystemMenus `json:"roles"`
				UniqueAuth        []string                   `json:"unique_auth"`
				Logo              string                     `json:"logo"`
				LogoSquare        string                     `json:"logo_square"`
				Version           string                     `json:"version"`
				NewOrderAudioLink string                     `json:"new_order_audio_link"`
				Queue             int                        `json:"queue"`
				Timer             int                        `json:"timer"`
				SiteName          string                     `json:"site_name"`
				SiteFunc          string                     `json:"site_func"`
			}{
				Token:             token,
				ExpiresTime:       facades.Config().Env("JWT_TTL"),
				UserInfo:          admin,
				Menus:             menus,
				UniqueAuth:        unique_auth,
				Logo:              "",
				LogoSquare:        "",
				Version:           "v1.0",
				NewOrderAudioLink: "0",
				Queue:             0,
				Timer:             0,
				SiteName:          "芽豆后台管理",
				SiteFunc:          "test",
			},
		})
	}
}
